--
-- Author: yawei.zhu
-- Date: 2018-09-05 18:00:51
--
-- PrestigeShopModel
--

local Goods = import(".Goods")
local FileUtils = cc.FileUtils:getInstance()

local fileName = string.getModeName(...)
local ClassRef = class(fileName, app.mvc.ModelBase)

local ItemNum =  5 -- 声望商店的菜单栏每页显示多少个商店

function ClassRef:ctor(data)
    self.super.ctor(self, data)
end

function ClassRef:init()
	-- 第一次进入某个商店请求一遍商品列表，然后存下来。下次再进入不再请求服务器
	self._shopData = {}
	self._shopList = nil
	self._buyNum = 1
end

-- 转换functionid为shopid
local function transFuncIdToShopId( functionId )
	if functionId >= Constant.FUNC_SHOP_FAME_1 and functionId <= Constant.FUNC_SHOP_FAME_3 then
		return 72011 + ( functionId - Constant.FUNC_SHOP_FAME_1 )
	elseif functionId >= Constant.FUNC_SHOP_FAME_4 and functionId <= Constant.FUNC_SHOP_FAME_6 then
		return 72021 + ( functionId - Constant.FUNC_SHOP_FAME_4 )
	elseif functionId >= Constant.FUNC_SHOP_FAME_7 and functionId <= Constant.FUNC_SHOP_FAME_9 then
		return 72031 + ( functionId - Constant.FUNC_SHOP_FAME_7 )
	elseif functionId >= Constant.FUNC_SHOP_FAME_10 and functionId <= Constant.FUNC_SHOP_FAME_12 then
		return 72041 + ( functionId - Constant.FUNC_SHOP_FAME_10 )
	end
end

-- 获取已开启的声望商店列表
function ClassRef:initPrestigeShopList()
	self._shopList = {}
	for i = Constant.FUNC_SHOP_FAME_1, Constant.FUNC_SHOP_FAME_12 do
		if UIHandler:isFunctionOpen(i) then
			local shopId = transFuncIdToShopId(i)
			local conf = GD:queryShopById(shopId)
			local name = conf and L("famename_"..tonumber(conf.fame))
			table.insert(self._shopList, {shopId = shopId, name = name})
		end
	end
	-- 世界声望商店放在最后
	if UIHandler:isFunctionOpen(Constant.FUNC_SHOP_FAME_99) then
		local conf = GD:queryShopById(72000)
		local name = conf and L("famename_"..tonumber(conf.fame))
		table.insert(self._shopList, {shopId = 72000, name = name})
	end
end

-- 获取已开启的声望商店总页数
function ClassRef:getCountPage()
	if self._shopList then
		return math.ceil(#self._shopList/ItemNum)
	end
end

-- 根据页数得到当前页的声望商店列表
function ClassRef:getShopsByPage(page)
	local list = {}
	local countPage = self:getCountPage()
	if page <= countPage then
		for i = (page-1)*ItemNum+1, page*ItemNum do
			if self._shopList[i] then
				table.insert(list, self._shopList[i])
			end
		end
	end
	return list	
end

-- 根据页数和索引找到商店id
function ClassRef:getShopIdByIndex(page, idx)
	local list = self:getShopsByPage(page)
	if list then
		return list[idx].shopId
	end
end

-- 根据商店id找到页数和索引
function ClassRef:getIndexByShopId(id)
	local page, index = 1, 1
	for i, v in ipairs(self._shopList) do
		if id == v.shopId then
			page = math.ceil(i / ItemNum)
			index = i - (page-1)*ItemNum
			break
		end
	end
	return page, index
end

-- 根据商店id获取商品列表
function ClassRef:getGoodsByShopId(id)
	return self._shopData[id]
end

function ClassRef:resetBuyNum()
	self._buyNum = 1
end

function ClassRef:buyNumPlus(goods)
	if goods.limitNum > 0 then
		self._buyNum = (self._buyNum < goods.leftNum) and (self._buyNum + 1) or self._buyNum
	else
		self._buyNum = (self._buyNum < 999) and (self._buyNum + 1) or self._buyNum
	end

	local totalPrice = goods.price * self._buyNum
	if totalPrice > self:getNumCount(goods) and self._buyNum > 1 then
		self._buyNum = self._buyNum - 1
	end
end

function ClassRef:buyNumMinus()
	self._buyNum = (self._buyNum > 1) and (self._buyNum - 1) or self._buyNum
end

function ClassRef:getBuyNumber()
	return self._buyNum
end

function ClassRef:getNumCount(goods)
	local itemData = UD:parseLootToBagItem(goods.cost[1])
	local iCount = 0
	if itemData.itemBagType == Enums.ItemBagType.item or itemData.itemBagType == Enums.ItemBagType.equip then -- 物品
		iCount = UD:getItemAmountByTid(itemData.tid)
	elseif itemData.itemBagType == Enums.ItemBagType.daibi then -- 货币
		iCount = UD:getDaibiValue( goods:getCostTypeId() )
	end
	return iCount
end

function ClassRef:getConditionStatusByGoods(goods)
	local conditionStatus = true
	local conditionStr = ""
	local siteConditionStr = ""
	local iconPath = nil
	local condition = goods.conds[1]
	if condition then
		if condition.condType == "Fame" then

			local fame = UD:getFameWithId(condition.condID)
			if fame then
				local level = fame.level
				local exp = fame.exp
				if tonumber(level) < tonumber(condition.condValue) then
					conditionStatus = false
				end
			end

			-- local fameC = GD:queryFameById(condition.condID)
   			--  		local fameName = fameC and L(fameC.name) or ""
    		local flvC = GD:queryFameLevelUpById(condition.condValue)
    		local flvName = flvC and L(flvC.name) or ""
			conditionStr = string.format(L("text_12200006"),flvName)
			local fameC = GD:queryFameById(condition.condID)
	        siteConditionStr = L("lua_code_text_314") .. L(fameC.name) .. " " .. flvName
	        iconPath = FileUtils:fullPathForFilename(GD:formatFameLevelIconFilePath(fameC.icon))
	    elseif condition.condType == "Level" then
	       	local needLevel = tonumber(condition.condID)
	        if UD:getPlayer().level < needLevel then
	        	conditionStatus = false
	        	--conditionStr = L("lua_code_text_438") .. needLevel
	        	siteConditionStr = L("lua_code_text_414") .. needLevel
	        	iconPath = Res.coinIconPath .. "common_icon_21.png"
			end
			conditionStr = L("lua_code_text_438") .. needLevel -- 英雄徽章商店和光芒徽章商店达到等级也要显示
	    elseif condition.condType == "Vip" then


	    elseif condition.condType == "Achievement" then
	        local achId = tonumber(condition.condID)
	        if not UD:isAchievementComplete(achId) then
	        	conditionStatus = false
	        	local achC = GD:getAchievementConfig(achId)
	        	local achName = achC and L(achC.name) or ""
	        	conditionStr = string.format(L("text_12200008"),achName)
	        	iconPath =  GD:getAchievementIconPath(achId)
	        end
		elseif condition.condType == "AchPoint" then
			local achPoint = tonumber(condition.condID)
			if achPoint > UD.player.achievementPoint then
				conditionStatus = false
				conditionStr = L("lua_code_text_196")..condition.condID
				iconPath = FileUtils:fullPathForFilename(Res.AchPointIconPath)
			end
			siteConditionStr = string.format(L("lua_code_text_150"), condition.condID)
	    elseif condition.condType == "None" then

		elseif condition.condType == "GuildTitle" then
			--公会官职相关 表中相对为7
			local guildModel = app:getInst("NewguildModel")
			local myguildInfo = guildModel:getMyGuildMemberInfo()
			local haveTitleCondition = (condition.condID > 0 or condition.condValue > 0)

			if haveTitleCondition and myguildInfo then

				if (condition.condID > 0 and myguildInfo:isEnoughTitle(condition.condID)) or
						(condition.condValue > 0 and myguildInfo:isEnoughTitle(condition.condValue)) then
					--满足条件
				else
					--不满足条件
					conditionStatus = false
					if condition.condID > 0 and condition.condValue > 0 then
						local tmpTitle1 = L(GD:queryPeerageById(condition.condID).name)
						local tmpTitle2 = L(GD:queryPeerageById(condition.condValue).name)
						conditionStr = string.format("%s%s,%s",L("text_12200015"),tmpTitle1,tmpTitle2)
						siteConditionStr = string.format("%s,%s",tmpTitle1,tmpTitle2)
						iconPath = string.format("%s%s%d.png",Res.guildPositionIconPath,"guild_shopjw_",tonumber(condition.condID))
					else
						local titleName = nil
						if condition.condID > 0 then
							titleName = L(GD:queryPeerageById(condition.condID).name)
							iconPath = string.format("%s%s%d.png",Res.guildPositionIconPath,"guild_shopjw_",tonumber(condition.condID))
						elseif condition.condValue > 0 then
							titleName = L(GD:queryPeerageById(condition.condValue).name)
							iconPath = string.format("%s%s%d.png",Res.guildPositionIconPath,"guild_shopjw_",tonumber(condition.condValue))
						end
						conditionStr = string.format("%s%s",L("text_12200015"),titleName)
						siteConditionStr = string.format("%s",titleName)
					end

				end
			end
		end

	end
	-- conditionStr,iconPath,siteConditionStr 只在 conditionStatus = false 的时候用到
	return conditionStatus,conditionStr,iconPath,siteConditionStr
end

function ClassRef:isMultiCost(goods)
    if #goods.cost > 1 then
        return true
    end
    return false
end

function ClassRef:transLootToItemData(goods)
    if not goods.cost then 
        return
    end
    if #goods.cost == 1 then 
        return goods.cost
    end
    local cost = {}
    for i, v in ipairs(goods.cost) do
        local iType = protobuf.enum_id("pb_loot.Loot.LootType", v.type)
        local itemF = iType .. "|" .. v.id .. "|" .. v.num
        local itemData = UD:parseRewardToBagItem(itemF)

        cost[#cost+1] = itemData
    end 
    return cost
end

-- 一生限购一次的商品购买完之后手动从列表中删除
function ClassRef:removeGoods(shopId, goods)
	local goodsData = self._shopData[shopId] or {}
    for i, v in ipairs(goodsData) do
		if tonumber(v.id) == tonumber(goods.id) then
			table.remove(goodsData, i)
			self._shopData[shopId] = goodsData
            return
		end
	end
end

function ClassRef:updateShopData(shopId, goods)
	self._shopData[shopId] = {}
	for i, v in pairs(goods) do
		local good = Goods.new(v)
		if good.show then
			table.insert(self._shopData[shopId], good)
		end
	end
end
------------------------ receive ------------------------


------------------------ request ------------------------
-- 查询商店商品列表
function ClassRef:reqPrestigeShopGoods(shopId)
	if not shopId then return end
	local function reqCallBack()
		EM:notify(ViewEvent.Shop_onQueryGoodsSuccess)
	end
	if self._shopData[shopId] then
		executeFunc(reqCallBack)
		return
	end
	app.session:request("pb_query.C2S_QueryShops", {shopIds = {shopId}}, function(msg)
		-- dump(msg, "pb_query.C2S_QueryShops")
		for _, shop in ipairs(msg.shops) do
			local sid = shop.shopId
			self._shopData[sid] = {}
			for i,v in ipairs(shop.goods) do
				local good = Goods.new(v)
				if good.show then
					table.insert(self._shopData[sid], good)
				end
			end
		end
		executeFunc(reqCallBack)
	end)
end

-- 购买商品
function ClassRef:C2S_BuyGoodsRequest(goodsId, num, shopId)
	local param = {npcUid = self.mNpcId,npcId = self.mNpcId,goodsId = goodsId,num = num}
	app.session:request("action.C2S_BuyGoods", param, function(msg)
		if not msg or not msg.goods then return end
		local id = msg.goods.id
		local newGoods = Goods.new(msg.goods)
		local goodsData = self._shopData[shopId]
		for i, goods in ipairs(goodsData) do
			if tonumber(goods.id) == tonumber(id) then
				goods:read(newGoods)
				EM:notify(ViewEvent.Shop_onBuyGoodsSuccess, goods)
				if goods.numType == "OneLifeLimit" and goods.leftNum <= 0 then
					self:removeGoods(shopId, goods)
					EM:notify(ViewEvent.Shop_onQueryGoodsSuccess)
				end
				app:popMessage("buySuccess")
				return
			end
		end
	end)
end

return ClassRef
